import { Component, EventEmitter, Injector, Output, ViewChild } from '@angular/core';
import { CopyViewInput, NameValue, PagedCustomConfigDto, PageViewServiceProxy } from '@shared/service-proxies/service-proxies';
import { ModalDirective } from 'ngx-bootstrap/modal';
import { finalize } from 'rxjs/operators';
import { AppModalComponentBase } from '@shared/common/app-modal-component-base';

@Component({
    selector: 'copy-pageview-modal',
    templateUrl: './copy-pageview-modal.component.html'
})
export class CopyPageViewModalComponent extends AppModalComponentBase {

    @ViewChild('modal', { static: true }) modal: ModalDirective;
    @Output() callback: EventEmitter<any> = new EventEmitter<any>();

    saving = false;
    loading = false;

    title: string;

    selectedValue: string ='';
    options: NameValue[] = [];
    idList: string[] = [];

    constructor(
        injector: Injector,
        private _pageViewServiceProxy: PageViewServiceProxy
    ) {
        super(injector);
    }


    show(idList: string[]) {
        this.idList = idList;
        this.modal.show();

        this.loading = true;
        this._pageViewServiceProxy.getFrontendPageListForCopyOp()
        .pipe(finalize(() => this.loading = false))
        .subscribe(result=> {
            this.options  = result;
        });
    }

    close(): void {
        this.modal.hide();
    }

    save() {
        if (this.selectedValue) {
            this.saving = true;
            const temp = this.selectedValue.split(',');
            const moduleId = temp[0];
            const pageId = temp[1];

            let input = new CopyViewInput({
                toFrontendPageId: pageId,
                idList: this.idList
            });

            this._pageViewServiceProxy.copyView(input)
            .pipe(finalize(() => this.saving = false))
            .subscribe(result=> {
                this.notify.success(this.l('CopySuccessfully'));
                this.callback.emit({ pageId: pageId, moduleId: moduleId});
                this.close();
            });
        }
    }
}
